//
// Created by hsj on 2024-1-8.
// 域名获取ip地址
//

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#ifdef WIN32
//windows minGW64
//inet_ntop函数：_WIN32_WINNT
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0600
#include <winsock2.h>
#include <ws2tcpip.h>
//#pragma comment(lib,"ws2_32.lib")
#else
//linux  gcc
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#endif
#define BUF_SIZE 30
void error_handling(char *message);

int main(int argc, char *argv[]){
    int i;
    /**
     *
     struct hostent {
            char * h_name ;//official name
            char **h_aliases ; //alias list
            int h_addrtype;//host address type
            int h_length;//address length
            char **h_addr_list;//address list
        }
     *
     */
    struct hostent *host ;

    host=gethostbyname("www.ynjsedu.cn");

    if(!host)
        error_handling( "gethost... error");

    printf("Official name: %s \n", host->h_name);

    for(i=0; host->h_aliases[i]; i++)
        printf("Aliases %d: %s \n", i+1, host->h_aliases[i]);

    printf("Address type: %s \n",(host->h_addrtype==AF_INET)?"AF_ INET":"AF_ INET6");

    //对应的ip地址，可能多个
    for(i=0; host->h_addr_list[i]; i++)
        printf("IP addr %d: %s \n", i+1,inet_ntoa(*(struct in_addr* )host->h_addr_list[i]));

    return EXIT_SUCCESS;
}

void error_handling( char *message){
    fputs (message, stderr);
    fputc('\n', stderr);
    exit(1);
}